package com.mbf.crm.controller.system;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.apache.commons.codec.digest.DigestUtils;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mbf.crm.common.AjaxResult;
import com.mbf.crm.common.DataGrid;
import com.mbf.crm.common.MySpecification;
import com.mbf.crm.common.MySpecification.Cnd;
import com.mbf.crm.model.dao.MemberDao;
import com.mbf.crm.model.dao.RoleDao;
import com.mbf.crm.model.domain.Member;
import com.mbf.crm.model.domain.Role;



/**
 * 用户控制管理器
 * @author 晏鼠  张劲松
 *
 */
@Controller
@RequestMapping("/system/member")
//一些只读不需要提交事务
@Transactional(readOnly = true)
public class MemberController {

	Logger logger = Logger.getLogger(MemberController.class);
	
	@Autowired
	private MemberDao memberDao;
	
	@Autowired
	private RoleDao roleDao;
	
	@Value("${crm.system.super-user-id}")
	Long superUserId;
	
	@RequestMapping
	public void index(){
		
	}
	
	@RequestMapping("/list")
	@ResponseBody
	public DataGrid<Member> list(int page,int rows, String userName,String realName,String telephone){
		@SuppressWarnings("deprecation")
		PageRequest pr = new PageRequest(page - 1, rows);
		//使用自定义的复杂查询
		@SuppressWarnings({ "rawtypes", "unchecked" })
		Page pageData = memberDao.findAll(new MySpecification<Member>().and(
				Cnd.like("userName", userName),
				Cnd.like("realName", realName),
				Cnd.like("telphone", telephone)
				).asc("id"),pr);
		return new DataGrid<Member>(pageData);
	}
	
	@RequestMapping("/form")
	public void form (Long id,Model model){
		if(id != null){
			ObjectMapper mapper = new ObjectMapper();
			Member member = memberDao.findOne(id);
			try{
				model.addAttribute("member", mapper.writeValueAsString(member));
			}catch(JsonProcessingException e){
				logger.error("json转换出错",e);
			}
		}
	}
	
	@RequestMapping("/check")
	@ResponseBody
	public boolean check(String userName){
		return memberDao.countByUserName(userName) == 0;
	}
	
	@RequestMapping("/roles")
	@ResponseBody
	public List<Role> roles(){
		return roleDao.findByStatus(true);
	}
	
	@RequestMapping({"/save","/update"})
	@Transactional
	@ResponseBody
	public AjaxResult save(@Valid Member member,Long[] roles,BindingResult br){
		if(br.hasErrors()){
			logger.error("对象校验失败：" + br.getAllErrors());
			return new AjaxResult(false).setData(br.getAllErrors());
		}else{
			if(member.getId() != null){
				//不在这里更新角色或密码
				Member orig = memberDao.findOne(member.getId());
				//理论上这里是一定要找得到对象的
				if(orig != null){
					member.setPassword(orig.getPassword());
				}
			}else{
				//默认密码
				member.setPassword(DigestUtils.sha256Hex("0000"));
			}
			//处理角色的关联
			if(roles != null && roles.length > 1){
				List<Role> rolesList = new ArrayList<Role>();
				for (Long rid : roles) {
					if(rid != null){
						rolesList.add(roleDao.findOne(rid));
					}
				}
				member.setRoles(rolesList);
			}
			return new AjaxResult();
		}
		
	}
	
	
	@RequestMapping("/delete")
	@Transactional
	@ResponseBody
	public AjaxResult resetPassword(Long id){
		try{
			if(superUserId != id){
				memberDao.deleteById(id);
			}else{
				return new AjaxResult(false, "管理员不能删除");
			}
		}catch(Exception e){
			return new AjaxResult(false).setMessage(e.getMessage());
		}
		return new AjaxResult();
	}
	
}
